package com.linkage.educloud.ah.config;


import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;

import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.data.Ws;
import com.zzhou.common.library.util.LogUtils;

import java.util.List;


/**
 * Created by 周振 on 2017/5/31.
 */

public class AccountConfig {
    private static AccountData _account;
    private MyContentObserver observer;
    private ContentResolver cr;
    private static AccountConfig mAccountConfig;

    private AccountConfig(Context context) {
        notifyAccountChanged();
        observer = new MyContentObserver(new Handler());
        cr = context.getContentResolver();
        //注册内容提供器观察者对象
        cr.registerContentObserver(Ws.AccountTable.CONTENT_URI, true, observer);
    }

    public static AccountConfig initialize(Context context) {
        if (mAccountConfig == null) {
            synchronized (AccountConfig.class) {
                if (mAccountConfig == null) {
                    mAccountConfig = new AccountConfig(context);
                }
            }
        }
        return mAccountConfig;
    }

    /*获取登录用户*/
    public static AccountData getLoginAccount() {
        if (_account == null) {
            LogUtils.d("account is null, requery");
            _account = MyApplication.getInstance().getResovler().getLoginAccount();
        } else {
            LogUtils.d("name = " + _account.getLoginAccount());
        }
        return _account;
    }

    /*获取最后一次登录用户*/
    public static AccountData getLastAccount() {
        List alist = MyApplication.getInstance().getResovler().getLastAccount();
        if (alist != null && alist.size()>0) {
           return MyApplication.getInstance().getResovler().getLastAccount().get(0);
        }
        return null;
    }

    public static synchronized void unRegisterAccount() {
        MyApplication.getInstance().getResovler().clearAccount();
        notifyAccountChanged();
    }

    public static synchronized void notifyAccountChanged() {
        _account = MyApplication.getInstance().getResovler().getLoginAccount();
        if (_account == null) {
            LogUtils.d("_account is null");
        } else {
            LogUtils.d("_account is " + _account.getLoginAccount());
        }
    }

    /**
     * 内容提供器观察者对象   监听响应需要一些时间，如果更新后立马就要变更页面，手动掉notifyAccountChanged()
     *
     * @author
     */
    class MyContentObserver extends ContentObserver {

        public MyContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            notifyAccountChanged();
            LogUtils.i("AccountData changed 更新数据");
        }
    }
}
